﻿using FastCloud.Base;
using FastCloud.Base.Attribute;
using FastCloud.Base.Config;
using FastCloud.Base.Desgin;
using FastCloud.Base.Entity;
using FastCloud.DMP.DB;
using FastCloud.DMP.Entity;
using FastIOC.Attribute;
using FastORM.Handle;
using FastUtil.Config;
using FastUtil.Convert;
using FastUtil.Data;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using System.Xml;

namespace FastCloud.Controllers.DMP
{
    [Route("frame/dmp/codemain")]
    public class CodeMainController : BaseController
    {
        [AutoWired]
        private DB_CodeMain DB_CodeMain;
        [AutoWired]
        private DB_CodeItem DB_CodeItem;

        [Route("list")]
        public IActionResult List()
        {
            return View("~/Views/DMP/CodeMain/CodeMain_List.cshtml");
        }
        [Route("add")]
        public IActionResult Add()
        {
            return View("~/Views/DMP/CodeMain/CodeMain_Add.cshtml");
        }
        [Route("edit")]
        public IActionResult Edit()
        {
            return View("~/Views/DMP/CodeMain/CodeMain_Edit.cshtml");
        }

        [Route("oplist"), HttpPost]
        public IActionResult OpList()
        {
            string CodeName = ValueConvert.ConvertToString(GetFormParam("CodeName"));
            string GroupGuid = ValueConvert.ConvertToString(GetFormParam("GroupGuid"));
            return Result.OK(DB_CodeMain.SelectPage(CodeName, GroupGuid));
        }

        [Route("oplistall"), HttpPost]
        public IActionResult OpListAll()
        {
            return Result.OK(DB_CodeMain.SelectAll());
        }

        [Route("opinsert"), HttpPost]
        public IActionResult OpInsert(Frame_CodeMain Entity)
        {
            if (DB_CodeMain.ExistCodeMain(Entity.CodeName))
            {
                return Result.Error("已存在相同名称的代码项！");
            }
            else
            {
                DB_CodeMain.Insert(Entity);
                return Result.OK();
            }
        }

        [Route("opupdate"), HttpPost]
        public IActionResult OpUpdate(Frame_CodeMain Entity)
        {
            if (DB_CodeMain.ExistCodeMain(Entity.CodeGuid, Entity.CodeName))
            {
                return Result.Error("已存在相同名称的代码项！");
            }
            else
            {
                DB_CodeMain.UpdateByID(Entity);
                return Result.OK();
            }
        }

        [Route("opdetail"), HttpPost]
        public IActionResult OpDetail()
        {
            string CodeGuid = ValueConvert.ConvertToString(GetFormParam("CodeGuid"));
            return Result.OK(DB_CodeMain.SelectOne(CodeGuid));
        }

        [Route("opbatchdelete"), HttpPost]
        public IActionResult OpBatchDelete()
        {
            string KeyID = ValueConvert.ConvertToString(GetFormParam("KeyID"));
            DB_CodeMain.DeleteBatch(KeyID.TrimEnd(';').Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries).ToList());
            return Result.OK();
        }

        [Route("exportxml"), HttpGet]
        public ContentResult ExportXML()
        {
            ContentResult result = new ContentResult();
            string KeyID = ValueConvert.ConvertToString(GetRequestParam("KeyID"));
            List<string> KeyGuidList = KeyID.TrimEnd(';').Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries).ToList();
            XmlDocument Doc = new XmlDocument();
            //创建根节点    
            XmlNode Root = Doc.CreateElement("ExportFile");
            ExportFileInfo FileInfo = new ExportFileInfo("DMPCode");
            XmlNode FileInfoNode = Doc.CreateElement("FileInfo");
            FileInfoNode.InnerXml = StructConvert.ConvertEnity2InnerXml(FileInfo);
            Root.AppendChild(FileInfoNode);
            foreach (string KeyGuid in KeyGuidList)
            {
                Frame_CodeMain Entity = DB_CodeMain.SelectOne(KeyGuid);
                List<Frame_CodeItem> CodeItemEntityList = DB_CodeItem.SelectCodeItemListByMainGuid(Entity.CodeGuid);
                XmlNode CodeMain = Doc.CreateElement("CodeMain");
                XmlNode CodeMainDetail = Doc.CreateElement("CodeMainDetail");
                CodeMainDetail.InnerXml = StructConvert.ConvertEnity2InnerXml(Entity);
                CodeMain.AppendChild(CodeMainDetail);
                XmlNode CodeItemList = Doc.CreateElement("CodeItemList");
                foreach (Frame_CodeItem Item in CodeItemEntityList)
                {
                    XmlNode CodeItem = Doc.CreateElement("CodeItem");
                    CodeItem.InnerXml = StructConvert.ConvertEnity2InnerXml(Item);
                    CodeItemList.AppendChild(CodeItem);
                }
                CodeMain.AppendChild(CodeItemList);
                Root.AppendChild(CodeMain);
            }
            Doc.AppendChild(Root);
            result.Content = StructConvert.ConvertXml2String(Doc);
            result.ContentType = "text/xml";
            return result;
        }

        [Route("importxml"), HttpPost]
        [Transitional]
        public virtual IActionResult ImportXML()
        {
            IFormFileCollection FileList = Request.Form.Files;
            if (FileList != null && FileList.Count > 0)
            {
                FormFile file = (FormFile)FileList[0];
                //暂存文件
                string FilePath = CloudUtil.GetAttachUploadPath("DMPCodeImport") + "/" + GenerateUtil.GenerateUnitGuid() + System.IO.Path.GetExtension(file.FileName);
                using (FileStream fstream = new FileStream(FilePath, FileMode.OpenOrCreate, FileAccess.ReadWrite))
                {
                    file.CopyTo(fstream);
                }
                //解析
                StreamReader Reader = new StreamReader(FilePath, System.Text.Encoding.UTF8);
                string StramReader = Reader.ReadToEnd().Trim();
                XmlDocument Doc = new XmlDocument();
                Doc.LoadXml(StramReader);
                XmlNode FileInfoNode = Doc.SelectSingleNode("/ExportFile/FileInfo");
                ExportFileInfo FileInfo = StructConvert.ConvertXMLNode2Entity<ExportFileInfo>(FileInfoNode);
                if (FileInfo.FileType == "DMPCode")
                {
                    XmlNodeList CodeMainNodeList = Doc.SelectNodes("/ExportFile/CodeMain");
                    foreach (XmlNode CodeMainNode in CodeMainNodeList)
                    {
                        XmlNode CodeDetailNode = CodeMainNode.SelectSingleNode("CodeMainDetail");
                        Frame_CodeMain CodeMain = StructConvert.ConvertXMLNode2Entity<Frame_CodeMain>(CodeDetailNode);
                        DB_CodeMain.DeleteByID(CodeMain.CodeGuid);
                        DB_CodeMain.Insert(CodeMain);
                        XmlNodeList CodeItemNodeList = CodeMainNode.SelectNodes("CodeItemList/CodeItem");
                        foreach (XmlNode CodeItemNode in CodeItemNodeList)
                        {
                            Frame_CodeItem CodeItem = StructConvert.ConvertXMLNode2Entity<Frame_CodeItem>(CodeItemNode);
                            DB_CodeItem.Insert(CodeItem);
                            //throw (new Exception("1111"));
                        }
                    }
                }
                else
                {
                    return Result.Error("XML文件类型不正确");
                }
            }
            else
            {
                return Result.Error("未选择文件");
            }
            return Result.OK();
        }
    }
}
